package com.chengqs.controller;

import com.chengqs.pojo.R;
import com.chengqs.pojo.entity.User;
import com.chengqs.service.UserService;
import com.chengqs.util.EmailUtil;
import com.chengqs.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private EmailUtil emailUtil;

    @Autowired
    private RedisTemplate redisTemplate;


    @GetMapping("sendCode")
    public R sendCode(String email){
        //调用login方法
        //根据邮箱查找用户
        User user = userService.login(email);

        //判断user是否为null
        if(user == null)
            return R.error("邮箱不存在");

        //邮箱是存在的 - 执行邮箱发送的东西.
        int n = (int) (Math.random()*90000+10000);
        String serverCode = String.valueOf(n);
        log.info("serverCode:"+serverCode);
        emailUtil.send(email,serverCode);


        /*//获取HttpSession对象
        //session是属于tomcat内部的空间,每个客户端都会拥有自己的session空间 - 内存中的区域
        HttpSession session = request.getSession();
        //将每个email和serverCode绑定在一起存储到session空间
        //存储的数据的格式是key,value形式
        session.setAttribute(email,serverCode);*/

        redisTemplate.opsForValue().set(email,serverCode,1, TimeUnit.MINUTES);

        return R.success(user);
    }

    @PostMapping("login")
    public R login(String email,String code,HttpServletRequest request){
        //1. 判断email是否存在
        User user=userService.login(email);
        if(user == null)
            return R.error("邮箱不存在");
        //2. email是存在的
        //根据email来获取它对应的serverCode
        // HttpSession session = request.getSession();
        // String serverCode = (String) session.getAttribute(email);
        //比较
        String serverCode = (String) redisTemplate.opsForValue().get(email);

        if(serverCode == null){
            return R.error("sorry,验证码已经过期了");
        }

        if(!serverCode.equals(code)){
            return R.error("sorry,验证码不正确");
        }

        //生成一个token
        String token = JwtUtil.geneJsonWebToken(user);

        return R.success(token);
    }
}
